package fr.cnam.projetSiw.server.geolocation;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fr.cnam.projetSiw.client.services.GeolocatorService;
import fr.cnam.projetSiw.shared.City;

public class GeolocatorServiceImpl extends RemoteServiceServlet implements GeolocatorService{

	private static final int IND_FIRST_TYPE = 3;
	/**
	 * 
	 */
	private static final long serialVersionUID = 4032337072766307156L;
	
	@Override
	public City getCity(String lon, String lat) {
			String latLong = lat+","+lon;
			String cityName="";
			String country ="";
			City city = null;
			try{
				URL url = new URL("http://maps.googleapis.com/maps/api/geocode/xml?latlng="+latLong+"&sensor=false");
				URLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setDoOutput(true);
				//recuperation du XML retourné par le web service
				InputStream openStream = conn.getInputStream();
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document doc = db.parse(openStream);
				//On recupre tous les sous elements address component pour recuperer la ville
				NodeList adress = doc.getElementsByTagName("address_component");
				for(int i=0 ; i<adress.getLength(); i++){
					String[] subNodes = adress.item(i).getTextContent().split("\n");
					String type =  subNodes[IND_FIRST_TYPE].replaceAll(" ", "");
					if(type.equals("locality")){
						cityName = subNodes[1].replace(" ", "");
					}
					else if(type.equals("country")){
						country = subNodes[1].replace(" ", "");
					}
				}
				if(adress.getLength()>0)
					city = new City(cityName, country);
			}
			catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}
		return city;
	}

}
